package com.geovis.emergency.spd.controller.custom;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.geovis.common.core.api.Result;
import com.geovis.common.mybatis.page.PageParam;
import com.geovis.emergency.spd.biz.command.service.MasterialinfoService;
import com.geovis.emergency.spd.biz.command.service.TfService;
import com.geovis.emergency.spd.biz.custom.service.ITyphoonService;
import com.geovis.emergency.spd.entity.command.pojo.dto.MasterialDTO;
import com.geovis.emergency.spd.entity.command.pojo.vo.OdsTyphoonVO;
import com.geovis.emergency.spd.entity.custom.entity.ResourceResponseDto;
import com.geovis.emergency.spd.entity.custom.entity.ResourceSearchFormDTO;
import com.geovis.emergency.spd.entity.custom.entity.ResourceSearchResultDTO;
import com.geovis.emergency.spd.entity.custom.entity.ResourceTreeDto;
import com.geovis.emergency.spd.entity.pc.pojo.vo.TyphoonVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.lang.reflect.Array;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 公共接口
 * </p>
 *
 * @author Lonsho
 * @version 1.0
 * @date 2022/6/10
 */
@RestController
@RequestMapping("/custom")
@RequiredArgsConstructor
@Api(value = "公共接口", tags = "公共接口接口")
@Slf4j
@Validated
public class CustomController {
    @Value("${typhoon.path}")
    private String typhoonPath;

    private final ITyphoonService typhoonService;

    private final TfService tfService;

    @Value("${geovis.tree-file}")
    private String treeFile;

//    private final String treeFileName="/mnt/vos-ev6rjhbg/project/chengyang/zjglyzt/data/tree.json";

    @Value("${geovis.resource-url}")
    private String resourceUrl;

    private final MasterialinfoService masterialinfoService;

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "获取台风列表", notes = "获取台风列表")
    @PostMapping({"/getTyphoonList"})
    public Result<List<TyphoonVO>> getTyphoonList(){

        return Result.ok(typhoonService.getTyphoonList());
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "获取台风", notes = "获取台风")
    @PostMapping({"/getTyphoon/{typhoonId}"})
    public Result<OdsTyphoonVO> getTyphoon(@PathVariable("typhoonId") String typhoonId){
        OdsTyphoonVO typhoon = tfService.getTyphoon(typhoonId);
        if (ObjectUtil.isNotNull(typhoon)){
            return Result.ok(typhoon);
        }
        return Result.failed("获取不到台风数据");
    }

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "获取应急资源树", notes = "获取应急资源树")
    @GetMapping({"/resource/getTreeList"})
    public Result<List<ResourceTreeDto>> getTreeList(){
        return Result.ok(getTree());
    }

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "获取物资仓库明细", notes = "获取物资仓库明细")
    @GetMapping({"/masterial/getMasterialinfos"})
    public Result<List<MasterialDTO>> getMasterialinfos(String depotId){
        return Result.ok(masterialinfoService.getMasterialinfos(depotId));
    }

    private List<ResourceTreeDto> getTree()
    {
//        String fileName="/mnt/geovis/chengyang/data/tree.json";
//        String fileName="D:\\work\\城阳项目\\tree.json";
        String jsonData= JSONUtil.readJSON(new File(treeFile), Charset.defaultCharset()).toString();
        return JSONUtil.toList(jsonData,ResourceTreeDto.class);
    }


    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "获取应急资源树", notes = "获取应急资源树")
    @PostMapping({"/resources/listPage"})
    public Result listPage(@RequestBody PageParam<ResourceSearchFormDTO> params){
        List<ResourceTreeDto> treeDtos=getTree();
        String typeCode=params.getQuery().getTypeCode();
        ResourceTreeDto selectNode=treeDtos.stream().filter(node->node.getId().equals(typeCode)).findFirst().get();
        Double pointLat=params.getQuery().getLatitude();
        Double pointLon=params.getQuery().getLongitude();
        //递归找出子节点

        List<ResourceSearchResultDTO> result=new ArrayList<>();
        findChild(treeDtos,selectNode,result,pointLat,pointLon);
//        if(CollectionUtils.isEmpty(leafNodes))
//        {
//            return null;
//        }
        return Result.ok(result);
    }

    private void findChild(List<ResourceTreeDto> treeDtos,ResourceTreeDto parentNode,List<ResourceSearchResultDTO> resultData,Double pointLat,Double pointLon)
    {
        List<ResourceTreeDto> childNodes= treeDtos.stream().filter(node->node.getParentId().equals(parentNode.getId())).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(childNodes))
        {
            log.info("---叶子节点 start---");
            List<ResourceSearchResultDTO> queryData=reqData(parentNode.getId());
            if(queryData==null)
            {
                return;
            }
            int condition = RandomUtil.randomInt(1, 10);
            for(int x=0;x<queryData.size();x++)
            {
                ResourceSearchResultDTO dto=queryData.get(x);
                int i = RandomUtil.randomInt(1, 20);
                log.info("---randomInt i---"+i);
                Double d=Double.valueOf("0.00"+i);
                int distance = RandomUtil.randomInt(10, 50);
                dto.setDistance(Double.valueOf(distance+""));
                if(x==0)
                {
                    if(condition % 2==0)
                    {
                        dto.setLatitude(NumberUtil.add(pointLat,d));
                        dto.setLongitude(NumberUtil.add(pointLon,d));
                    }
                    else
                    {
                        dto.setLatitude(NumberUtil.sub(pointLat,d));
                        dto.setLongitude(NumberUtil.sub(pointLon,d));
                    }
//                    dto.setLongitude(NumberUtil.sub(pointLon,d));
                }
                else
                {
//                    dto.setLatitude(NumberUtil.sub(pointLat,d));
                    if(condition % 2==0)
                    {
                        dto.setLatitude(NumberUtil.sub(pointLat,d));
                        dto.setLongitude(NumberUtil.sub(pointLon,d));
                    }
                    else
                    {
                        dto.setLatitude(NumberUtil.add(pointLat,d));
                        dto.setLongitude(NumberUtil.add(pointLon,d));
                    }
                }
            }
            resultData.addAll(queryData);
            log.info("---叶子节点 end---");
            return;
        }
        for(ResourceTreeDto child:childNodes)
        {
            findChild(treeDtos,child,resultData,pointLat,pointLon);
        }
    }

    private List<ResourceSearchResultDTO> reqData(String typeCode)
    {
//        String url="http://10.1.110.96:8083/elasticsearch/resources/getList";

        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_JSON);
        RestTemplate restTemplate=new RestTemplate();
        Map<String, Object> bodyMap = new LinkedHashMap<>();
        bodyMap.put("typeCode", typeCode);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(bodyMap,header);
        ResponseEntity<ResourceResponseDto> response=restTemplate.exchange(resourceUrl, HttpMethod.POST, entity,ResourceResponseDto.class);
        if(response.getStatusCode()!= HttpStatus.OK)
        {
            log.error("请求失败！");
            log.error("body:{}", response.getBody());
            return null;
        }
        JSONArray array =JSONUtil.parseArray(response.getBody().getData());
        List<ResourceSearchResultDTO> resultDTOS=JSONUtil.toList(array,ResourceSearchResultDTO.class);
        return resultDTOS;

    }

}
